<?php
namespace app\common\controller;

use think\Controller;
use think\Db;
use think\Cache;

class ApiBase extends Controller {
    protected function _initialize() {
      parent::_initialize();
      define('CHARSET', "utf-8");
    }

    /** Send a Header
     *
     * @return  void
     *
     * @auther Doujia
     * Sep 26, 2011
     */
    public function json_header()
    {
        header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
        header("Content-type:text/plain;charset=" . CHARSET, true);
    }

    /**
     * Make a successfully message
     *
     * @param   mixed   $retval
     * @param   string  $msg
     *
     * @auther Doujia
     * Sep 26, 2011
     */
    public function json_result($retval = '', $msg = '', $jqremote = false)
    {
        if (! empty($msg)) {
            $msg = $msg;
        }
        $this->json_header();
        $json = ecm_json_encode(array('done' => true, 'msg' => $msg, 'retval' => $retval));
        if ($jqremote === false) {
            $jqremote = isset($_GET['jsoncallback']) ? trim($_GET['jsoncallback']) : false;
        }
        if ($jqremote) {
            $json = $jqremote . '(' . $json . ')';
        }
        header('Content-type: application/json');
        echo $json;
        exit;
    }

    /**
     * Make a error message by JSON format
     *
     * @param   string  $msg
     * @return  void
     *
     * @auther Doujia
     * Sep 26, 2011
     */
    public function json_error($msg = '', $retval = null, $jqremote = false)
    {
        //begin add by tongxuefen 2011-04-21 ajax 没有登录或登录超时
        if ($msg == 'login_please') {
            echo '<script language="javascript"> window.top.history.go(0);</script>';
            return;
        }
        //end add
        if (! empty($msg)) {
            $msg = $msg;
        }
        $result = array('done' => false, 'msg' => $msg);
        if( $msg == '请登录' or $msg == 'login_please'){
            $result = array('done' => false,  'reLogin' => true, 'msg' => $msg);
        }

        if (isset($retval))
            $result['retval'] = $retval;
        $this->json_header();
        $json = ecm_json_encode($result);
        if ($jqremote === false) {
            $jqremote = isset($_GET['jsoncallback']) ? trim($_GET['jsoncallback']) : false;
        }
        if ($jqremote) {
            $json = $jqremote . '(' . $json . ')';
        }
        header('Content-type: application/json');
        echo $json;
        exit;
    }
   
}